<template>
  <div class="system-config">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>系统配置管理</span>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="配置键">
            <el-input
              v-model="searchForm.configKey"
              placeholder="请输入配置键"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="配置名称">
            <el-input
              v-model="searchForm.configName"
              placeholder="请输入配置名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 操作按钮区域 -->
      <div class="action-area">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增配置
        </el-button>
        <el-button type="success" @click="handleRefreshCache">
          <el-icon><Refresh /></el-icon>
          刷新缓存
        </el-button>
        <el-button @click="goBack">
          <el-icon><Back /></el-icon>
          返回
        </el-button>
      </div>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="configKey" label="配置键" min-width="150" show-overflow-tooltip />
        <el-table-column prop="configName" label="配置名称" min-width="120" show-overflow-tooltip />
        <el-table-column prop="configValue" label="配置值" min-width="200" show-overflow-tooltip />
        <el-table-column prop="configType" label="配置类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getConfigTypeTag(row.configType)">
              {{ row.configType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isSystem" label="系统配置" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isSystem ? 'danger' : 'success'">
              {{ row.isSystem ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="150" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
                         <el-button
               v-if="!row.isSystem"
               type="danger"
               size="small"
               @click="handleDelete(row)"
             >
               <el-icon><Delete /></el-icon>
               删除
             </el-button>
             <el-button
               v-else
               type="info"
               size="small"
               disabled
               title="系统配置项不可删除"
             >
               <el-icon><Lock /></el-icon>
               锁定
             </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-area">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
                 <el-form-item label="配置键" prop="configKey">
           <el-input
             v-model="form.configKey"
             placeholder="请输入配置键"
             :disabled="form.id !== undefined || form.isSystem"
           />
           <div v-if="form.isSystem" style="margin-top: 4px; color: #e6a23c; font-size: 12px;">
             <el-icon><Lock /></el-icon>
             系统配置项键名不可修改
           </div>
         </el-form-item>
        <el-form-item label="配置名称" prop="configName">
          <el-input
            v-model="form.configName"
            placeholder="请输入配置名称"
          />
        </el-form-item>
        <el-form-item label="配置值" prop="configValue">
          <!-- 所有配置类型都使用开关控件 -->
          <el-switch
            v-model="form.configValue"
            :active-value="getActiveValue()"
            :inactive-value="getInactiveValue()"
            :active-text="getActiveText()"
            :inactive-text="getInactiveText()"
          />
          <!-- 显示当前配置值的详细信息 -->
          <div style="margin-top: 8px; color: #666; font-size: 12px;">
            <span>当前值: </span>
            <el-tag size="small" :type="getValueTagType()">
              {{ formatConfigValue(form.configValue) }}
            </el-tag>
          </div>
        </el-form-item>
                 <el-form-item label="配置类型" prop="configType">
           <el-select 
             v-model="form.configType" 
             placeholder="请选择配置类型" 
             style="width: 100%"
             :disabled="form.isSystem"
           >
             <el-option label="字符串" value="string" />
             <el-option label="数字" value="number" />
             <el-option label="布尔值" value="boolean" />
             <el-option label="JSON" value="json" />
           </el-select>
           <div v-if="form.isSystem" style="margin-top: 4px; color: #e6a23c; font-size: 12px;">
             <el-icon><Lock /></el-icon>
             系统配置项类型不可修改
           </div>
         </el-form-item>
                 <el-form-item label="系统配置" prop="isSystem">
           <el-switch
             v-model="form.isSystem"
             active-text="是"
             inactive-text="否"
             :disabled="form.id !== undefined"
           />
           <div style="margin-top: 8px; color: #666; font-size: 12px;">
             <span v-if="form.isSystem">系统配置项：</span>
             <span v-else>用户配置项：</span>
             <el-tag size="small" :type="form.isSystem ? 'danger' : 'success'">
               {{ form.isSystem ? '不可删除，系统核心配置' : '可删除，用户自定义配置' }}
             </el-tag>
             <div v-if="form.id !== undefined" style="margin-top: 4px; color: #e6a23c; font-size: 12px;">
               <el-icon><Lock /></el-icon>
               编辑时系统配置标识不可修改
             </div>
           </div>
         </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            placeholder="请输入描述"
            type="textarea"
            :rows="2"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, Back, Lock } from '@element-plus/icons-vue'
import {
  getConfigList,
  createConfig,
  updateConfig,
  deleteConfig,
  refreshConfigCache
} from '@/api/system'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const tableData = ref([])

// 搜索表单
const searchForm = reactive({
  configKey: '',
  configName: ''
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const submitLoading = ref(false)
const formRef = ref()

// 表单数据
const form = reactive({
  id: undefined,
  configKey: '',
  configName: '',
  configValue: false, // 默认设置为false，对应开关的关闭状态
  configType: 'string',
  isSystem: false,
  description: ''
})

// 表单验证规则
const rules = {
  configKey: [
    { required: true, message: '请输入配置键', trigger: 'blur' },
    { pattern: /^[a-zA-Z][a-zA-Z0-9._-]*$/, message: '配置键格式不正确', trigger: 'blur' }
  ],
  configName: [
    { required: true, message: '请输入配置名称', trigger: 'blur' }
  ],
  configValue: [
    { required: true, message: '请设置配置值', trigger: 'change' }
  ],
  configType: [
    { required: true, message: '请选择配置类型', trigger: 'change' }
  ]
}

// 方法
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    }
    
    console.log('请求参数:', params)
    const response = await getConfigList(params)
    console.log('API响应:', response)
    
    if (response && response.code === 200 && response.data) {
      console.log('分页数据详情:', {
        records: response.data.records,
        total: response.data.total,
        current: response.data.current,
        size: response.data.size,
        pages: response.data.pages
      })
      tableData.value = response.data.records || []
      pagination.total = response.data.total || 0
      console.log('设置表格数据:', tableData.value)
      console.log('设置分页信息:', {
        current: pagination.current,
        size: pagination.size,
        total: pagination.total
      })
    } else {
      ElMessage.error(response?.message || '获取配置列表失败')
      tableData.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取配置列表失败:', error)
    ElMessage.error('获取配置列表失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    configKey: '',
    configName: ''
  })
  pagination.current = 1
  loadData()
}

const handleSizeChange = (size) => {
  console.log('分页大小改变:', size)
  pagination.size = size
  loadData()
}

const handleCurrentChange = (current) => {
  console.log('当前页改变:', current)
  pagination.current = current
  loadData()
}

const handleAdd = () => {
  dialogTitle.value = '新增配置'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑配置'
  // 深拷贝数据，避免直接修改原数据
  const formData = { ...row }
  
  // 根据配置类型转换值为开关状态
  if (formData.configType === 'boolean') {
    // 布尔值：true/false
    formData.configValue = formData.configValue === 'true' || formData.configValue === true
  } else if (formData.configType === 'number') {
    // 数字：大于0为开启，否则为关闭
    formData.configValue = Number(formData.configValue) > 0 ? 1 : 0
  } else if (formData.configType === 'string') {
    // 字符串：'enabled'/'true' 为开启，否则为关闭
    const value = String(formData.configValue).toLowerCase()
    formData.configValue = value === 'enabled' || value === 'true' ? 'enabled' : 'disabled'
  } else if (formData.configType === 'json') {
    // JSON：解析后检查enabled字段
    try {
      const parsed = JSON.parse(formData.configValue)
      formData.configValue = parsed.enabled ? '{"enabled": true}' : '{"enabled": false}'
    } catch {
      formData.configValue = '{"enabled": false}'
    }
  }
  
  Object.assign(form, formData)
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  // 检查是否为系统配置项
  if (row.isSystem) {
    ElMessage.warning('系统配置项不可删除，请谨慎操作')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除配置"${row.configName}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    try {
      const response = await deleteConfig(row.id)
      if (response.code === 200) {
        ElMessage.success('删除成功')
        loadData()
      } else {
        ElMessage.error(response.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleRefreshCache = async () => {
  try {
    const response = await refreshConfigCache()
    if (response.code === 200) {
      ElMessage.success('刷新缓存成功')
    } else {
      ElMessage.error(response.message || '刷新缓存失败')
    }
  } catch (error) {
    console.error('刷新缓存失败:', error)
    ElMessage.info('刷新缓存功能开发中...')
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    // 准备提交数据，根据类型转换值
    const submitData = { ...form }
    if (submitData.configType === 'boolean') {
      // 布尔值：转换为字符串
      submitData.configValue = String(submitData.configValue)
    } else if (submitData.configType === 'number') {
      // 数字：转换为字符串
      submitData.configValue = String(submitData.configValue)
    } else if (submitData.configType === 'string') {
      // 字符串：保持原值
      submitData.configValue = String(submitData.configValue)
    } else if (submitData.configType === 'json') {
      // JSON：保持原值
      submitData.configValue = String(submitData.configValue)
    }
    
    let response
    if (form.id) {
      // 编辑
      response = await updateConfig(submitData)
    } else {
      // 新增
      response = await createConfig(submitData)
    }
    
    if (response.code === 200) {
      ElMessage.success(form.id ? '更新成功' : '新增成功')
      dialogVisible.value = false
      loadData()
    } else {
      ElMessage.error(response.message || (form.id ? '更新失败' : '新增失败'))
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  } finally {
    submitLoading.value = false
  }
}

const resetForm = () => {
  Object.assign(form, {
    id: undefined,
    configKey: '',
    configName: '',
    configValue: false, // 重置为false，对应开关的关闭状态
    configType: 'string',
    isSystem: false,
    description: ''
  })
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

const goBack = () => {
  router.push('/system')
}

const getConfigTypeTag = (type) => {
  const typeMap = {
    string: '',
    number: 'success',
    boolean: 'warning',
    json: 'info'
  }
  return typeMap[type] || ''
}

// 获取开关的激活值
const getActiveValue = () => {
  switch (form.configType) {
    case 'boolean':
      return true
    case 'number':
      return 1
    case 'string':
      return 'enabled'
    case 'json':
      return '{"enabled": true}'
    default:
      return true
  }
}

// 获取开关的非激活值
const getInactiveValue = () => {
  switch (form.configType) {
    case 'boolean':
      return false
    case 'number':
      return 0
    case 'string':
      return 'disabled'
    case 'json':
      return '{"enabled": false}'
    default:
      return false
  }
}

// 获取开关的激活文本
const getActiveText = () => {
  switch (form.configType) {
    case 'boolean':
      return '启用'
    case 'number':
      return '开启'
    case 'string':
      return '启用'
    case 'json':
      return '启用'
    default:
      return '启用'
  }
}

// 获取开关的非激活文本
const getInactiveText = () => {
  switch (form.configType) {
    case 'boolean':
      return '禁用'
    case 'number':
      return '关闭'
    case 'string':
      return '禁用'
    case 'json':
      return '禁用'
    default:
      return '禁用'
  }
}

// 获取值标签的类型
const getValueTagType = () => {
  const value = form.configValue
  if (form.configType === 'boolean') {
    return value === true || value === 'true' ? 'success' : 'danger'
  } else if (form.configType === 'number') {
    return value > 0 ? 'success' : 'danger'
  } else if (form.configType === 'string') {
    return value === 'enabled' || value === 'true' ? 'success' : 'danger'
  } else if (form.configType === 'json') {
    try {
      const parsed = JSON.parse(value)
      return parsed.enabled ? 'success' : 'danger'
    } catch {
      return 'info'
    }
  }
  return 'info'
}

// 格式化配置值显示
const formatConfigValue = (value) => {
  if (form.configType === 'boolean') {
    return value === true || value === 'true' ? '启用' : '禁用'
  } else if (form.configType === 'number') {
    return value > 0 ? `开启 (${value})` : `关闭 (${value})`
  } else if (form.configType === 'string') {
    return value === 'enabled' || value === 'true' ? `启用 (${value})` : `禁用 (${value})`
  } else if (form.configType === 'json') {
    try {
      const parsed = JSON.parse(value)
      return parsed.enabled ? `启用 (${value})` : `禁用 (${value})`
    } catch {
      return `无效JSON (${value})`
    }
  }
  return String(value)
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.system-config {
  padding: 20px;
}

.card-header {
  font-weight: bold;
  color: #303133;
}

.search-area {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: center;
}

.action-area {
  margin-bottom: 20px;
}

.pagination-area {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
